<?php


namespace app\mweb\controller;


use app\admin\model\Staff;
use app\admin\model\UserList as user;
use app\admin\model\UserPvLog;
use app\common\Common;
use app\sys\service\GateCli;
use think\facade\Validate;
use think\Request;

class Chat extends Common
{
    // 发送消息
    public function sendInfo(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "to_user_no|用户编号" => "require",
            "chat_info|聊天消息" => "require",
            "store_id|店铺id" => "require",
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $staffInfo = $request->_user;
        $userInfo = \app\admin\model\User::where("no", $data["to_user_no"])->find();
        if (!$userInfo) {
            return failedJson("该用户不存在~");
        }
        $res = user::toUser($userInfo["id"],$userInfo["no"], $data["chat_info"], $staffInfo, $data["store_id"]);
        if($res) return failedJson($res);
        return successJson("success", "");
    }

    // 获取聊天消息
    public function getInfo(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "user_no|用户编号" => "require",
            "chat_id|聊天id" => "require",
        ]);

        $chatLogId = $request->param("chat_log_id", "0");
        $page = $request->param("page", 1);
        $limit = $request->param("limit", 10);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $staffInfo = $request->_user;

        $chatDate = \app\admin\model\Chat::where("user_no", $data["user_no"])->where("staff_id", $staffInfo["id"])->where("id", $data["chat_id"])->find();
        if (!$chatDate) {
            return failedJson("信息不存在~");
        }
        $list = user::getInfo($staffInfo["id"], $chatDate["user_id"], $data["chat_id"], $chatLogId, $page, $limit);
        return successJson("success", $list);
    }

    // 修改消息状态
    public function upInfoStatus(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "user_no|用户no" => "require",
            "chat_id|聊天id" => "require",
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $staffInfo = $request->_user;
        $userInfo = \app\admin\model\User::where("no", $data["user_no"])->find();
        if (!$userInfo) {
            return failedJson("用户不存在~");
        }
        $res = user::upStatus($data["chat_id"], $userInfo["id"], $staffInfo["id"], "staff");
        if ($res) {
            return failedJson($res);
        }
        // 发送信息
        $isMen = 0;
        if ($userInfo["mobile"]) $isMen = 1;
        $gate = new GateCli();
        $gate->staffUpNew($userInfo["no"], $userInfo["id"], $data["chat_id"], $isMen);

        return successJson("success", "修改成功");
    }
}